<template>
  <div class="student-view">
    <h1>学生答题界面</h1>

    <!-- 登录界面 -->
    <form @submit="login" v-if="!isLoggedIn">
      <div class="form-group">
        <label for="userType">用户类型</label>
        <div>
          <label v-for="type in ['individual', 'group']" :key="type">
            <input type="radio" v-model="userType" :value="type" :id="type" class="form-check-input" />
            <span class="form-check-label">{{ type === 'individual' ? '个人' : '小组' }}</span>
          </label>
        </div>
      </div>
      <div class="form-group" v-if="userType === 'individual'">
        <label for="selectedName">选择姓名</label>
        <select v-model="selectedName" class="form-control">
          <option v-for="name in names" :key="name" :value="name">{{ name }}</option>
        </select>
      </div>
      <div class="form-group" v-if="userType === 'group'">
        <label for="selectedGroupNames">选择小组成员</label>
        <select v-model="selectedGroupNames" multiple class="form-control">
          <option v-for="name in names" :key="name" :value="name">{{ name }}</option>
        </select>
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-primary">登录</button>
      </div>
    </form>

    <!-- 答题界面 -->
    <div v-else>
      <div class="current-question" v-if="currentQuestion">
      <h2>题目 {{ currentQuestionIndex + 1 }} / {{ questions.length }}</h2>
      <p>{{ currentQuestion.content }}</p>

      <!-- 答案输入区域 -->
      <textarea 
        v-model="studentAnswer" 
        rows="4" 
        placeholder="请输入你的答案"
        v-if="!currentQuestion.isSurvey"
        class="form-control"
      ></textarea>

      <!-- 问卷选项 -->
      <div v-else>
        <label v-for="(option, index) in surveyOptions" :key="index">
          <input type="radio" v-model="studentAnswer" :value="option" class="form-check-input" />
          <span class="form-check-label">{{ option }}</span>
        </label>
      </div>

      <!-- 导航按钮 -->
      <div class="navigation-buttons">
        <button 
          @click="prevQuestion" 
          :disabled="currentQuestionIndex === 0"
          class="btn btn-secondary"
        >上一题</button>

        <button 
          @click="submitAnswer"
          :disabled="currentQuestionIndex !== questions.length - 1"
          class="btn btn-primary"
        >提交答卷</button>

        <button 
          @click="nextQuestion"
          :disabled="currentQuestionIndex === questions.length - 1"
          class="btn btn-primary"
        >下一题</button>
      </div>
    </div>

    </div>
    <!-- 完成提示 -->
    <div class="completion-message" v-else>
      <h2>答题完成！</h2>
      <p>感谢你的参与，答题结果已提交。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import io from 'socket.io-client'

const questions = ref([])
const currentQuestionIndex = ref(0)
const studentAnswer = ref('')
const surveyOptions = ['非常同意', '同意', '一般', '不同意', '非常不同意']
const userType = ref('individual')
const selectedName = ref('')
const selectedGroupNames = ref([])
const names = ref([])
const isLoggedIn = ref(false)
const currentQuestion = ref(null)

// 获取题目列表
const fetchQuestions = async () => {
  console.log('正在获取题目列表')
  try {
    const response = await axios.get('/api/questions')
    questions.value = response.data
    currentQuestion.value = questions.value[0]
    console.log('成功获取题目列表，数量:', questions.value.length)
  } catch (error) {
    console.error('获取题目列表失败:', error)
  }
}

// 上一题
const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    currentQuestion.value = questions.value[currentQuestionIndex.value]
    studentAnswer.value = ''
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    submitAnswer(false)
    currentQuestionIndex.value++
    currentQuestion.value = questions.value[currentQuestionIndex.value]
    studentAnswer.value = ''
  }
}

// 提交答案
const submitAnswer = async (showMessage = true) => {
  console.log('正在提交答案:', {questionId: currentQuestion.value.id, answer: studentAnswer.value})
  try {
    await axios.post('/api/answers', {
      questionId: currentQuestion.value.id,
      answer: studentAnswer.value
    })
    console.log('答案提交成功')
    if (showMessage) {
      currentQuestion.value = null
    }
  } catch (error) {
    console.error('提交答案失败:', error)
  }
}

// 登录方法
const login = () => {
  if (userType.value === 'individual') {
    socket.emit('login', { type: 'individual', name: selectedName.value });
  } else {
    socket.emit('login', { type: 'group', names: selectedGroupNames.value });
  }
  isLoggedIn.value = true
}

// Socket.io连接和事件监听
const socket = io()
socket.on('connect', () => {
  socket.emit('request_students')
})
socket.on('names', (newNames) => {
  names.value = [...newNames]
});
socket.on('question', (question, options) => {
  currentQuestion.value = question;
  surveyOptions.value = options;
});

onMounted(() => {
  fetchQuestions()
  if (!socket.connected) socket.connect()
})
</script>

<style scoped>
.student-view {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 20px;
}

.form-control {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
}

.btn {
  padding: 10px 15px;
  margin-right: 10px;
}

.navigation-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.completion-message {
  text-align: center;
  margin-top: 50px;
}
</style>